import { action, observable, toJS } from 'mobx';
import { ListView, Toast, Tools } from 'weaver-mobile';
import { BrowserHrm, RouteLayout, Browser } from 'weaver-mobile-page';
import app from '../../../apis/app';
import { userType } from '../../../components/form/permission/type';

const { CHATGROUP, USER } = userType;
const getLabel = Tools.getLabel;

const dataSource = new ListView.DataSource({
  rowHasChanged: (row1, row2) => row1 !== row2,
});

export default class Store extends RouteLayout.Store {
  @observable selectedKey = '0';
  @observable sourceChatList = []; // 接口得到的数据，过滤的时候用 -- 最近聊天
  @observable chatList = [];
  @observable sourceGroupList = []; // 接口得到的数据，过滤的时候用 -- 群组
  @observable groupList = [];
  @observable chatValue = ''; // 搜索值
  @observable groupValue = ''; // 搜索值
  @observable chatLoading = false;
  @observable groupLoading = false;
  @observable browserHrmStore;
  @observable browserStore;
  @observable browserDeptStore;
  @observable browserSubcomStore;

  @observable isInEM = true; // 是否在e-mobile环境
  @observable hasMore = false; // group - 是否有下一页
  @observable currentPage = 1;
  @observable pageSize = 10;
  @observable totalcount = 0;
  @observable relatedGroupList = []; // 相关的群组
  @observable createNewGroupIds = ''; // 继续创建新的群聊的ids
  @observable dataSource = dataSource.cloneWithRows(toJS(this.groupList));
  @observable users = [];
  @observable chatGroup = [];
  @observable department = [];
  @observable subCompany = [];

  
  @action setChatList = (chatList) => this.chatList = chatList;

  @action init = (pathname) => {
    // path: 取RouteStore的path
    this.browserHrmStore = new BrowserHrm.Store({ route: pathname || '/form/permission/share', id: 'add' });
    this.browserDeptStore = new Browser.Store({ route: pathname || '/form/permission/share', id: 'browserDept' });
    this.browserSubcomStore = new Browser.Store({ route: pathname || '/form/permission/share', id: 'browserSubcom' });

    // this.initList(true);
    this.getLastChatList();
    const isInEM = window.em && typeof window.em.checkJsApi === 'function' && window.em.checkJsApi('sendMsg');
    if (!isInEM) {
      this.isInEM = false;
    }
  }

  @action setState = params => Object.keys(params).forEach(key => this[key] === params[key])

  @action resetGroupProps = () => {
    this.hasMore = false;
    this.currentPage = 1;
    this.totalcount = 0;
  }

  // @action initList = (isInit) => {
  //   this.getLastChatList();
  //   this.getGroupList({
  //     pagenum: 1,
  //     pagesize: this.pageSize,
  //   }, isInit);
  // }

  @action addShareMembers = (appid, value) => {
    return new Promise(resolve => {
      app.addShareMembers({
        appid: appid,
        data: JSON.stringify(value)
      }).then(() => {
        Toast.hide();
        this.throwSuccess();
        resolve();
      }).catch(() => {
        Toast.hide();
        this.throwError()
        resolve();
      })
    });
    
  }

  @action updateCurrentPage = page => this.currentPage = page;

  // 获取最近的对话列表
  @action getLastChatList = () => {
    this.chatLoading = true;
    Tools.callApi({
      url: '/api/ec/dev/share/getLastConversationList',
      method: 'GET',
      params: {},
    }).then((result) => {
      if (result.errcode === 0) {
        const that = this; 
        const openFrom = window.localStorage.getItem('openFrom');

        if (that.isInEM && window.em.checkJsApi('getTargetInfo') && openFrom !== 'workbench') {
           window.em.getTargetInfo({
            success: function (res) {
              // 如：{"targetType":0,targetId":"180","targetName":"张三","errMsg":"getTargetInfo:ok"}
              const { targetId, targetType } = res;
              if (String(targetType) === '0' || String(targetType) === '1') {
                let target_id = targetId;
                if (String(targetType) === '0') {
                  target_id = targetId.split('\|')[0];
                }

                Tools.callApi({
                  url: '/api/edc/app/form/getConversationInfo',
                  method: 'GET',
                  params: { conversationId: target_id, conversationType: targetType },
                }).then(resInfo => {

                  const { data } = resInfo;
                  let chatList = result.conversationlist || [];

                  if (data.id) {
                    const curr = {
                      target_id: data.id,
                      target_type: String(targetType),
                      target_name: data.name,
                      member_size: data.memberSize,
                      departmentName: data.departmentName,
                    }

                    const tmpUser = {
                      id: data.id,
                      lastname: data.name,
                      isSelect: true,
                      //icon: data.imgUrl,
                      member_size: data.memberSize,
                      type: String(targetType) === '0' ? USER : CHATGROUP,
                    }

                    chatList = chatList.filter(c => c.target_id !== target_id);
                    chatList.unshift(curr);
                    if (String(targetType) === '0') {
                      that.users = [tmpUser];
                    } else {
                      that.chatGroup = [tmpUser];
                    }
                  }

                  that.chatList = chatList;
                  that.sourceChatList = chatList;
                  that.chatLoading = false;
                });
              } else {
                that.chatList = result.conversationlist || [];
                that.sourceChatList = result.conversationlist || [];
                that.chatLoading = false;
              }
            },
            fail: () => {
              that.chatList = result.conversationlist || [];
              that.sourceChatList = result.conversationlist || [];
              that.chatLoading = false;
            }
          });
        } else {
          this.chatList = result.conversationlist || [];
          this.sourceChatList = result.conversationlist || [];
          this.chatLoading = false;
        }
      } else {
        this.chatLoading = false;
        this.throwError(result.errmsg);
      }
    }).catch(() => {
      this.chatLoading = false;
    });
  }

  // 获取最近群组列表
  @action getGroupList = (params = {}, isInit, isGetRelated, successCallback, failCallback) => {
    this.groupLoading = true;
    Tools.callApi({
      url: '/api/ec/dev/share/getGroupList',
      method: 'GET',
      params,
    }).then((result) => {
      if (result.errcode === 0) {
        const list = result.grouplist || [];
        if (isGetRelated) {
          this.relatedGroupList = list;
        } else {
          this.totalcount = result.totalcount;
          this.hasMore = result.totalpage > this.currentPage;
          this.groupList = isInit ? list : [
            ...this.groupList,
            ...list,
          ];
          this.dataSource = this.dataSource.cloneWithRows(toJS(this.groupList));
          this.groupLoading = false;
        }
        if (successCallback) successCallback(result);
        // this.sourceGroupList = result.grouplist || [];
      } else {
        this.throwError(result.errmsg);
        if (failCallback) failCallback();
      }
    });
  }

  // 获取群组成员列表
  @action getGroupMembers = id => (
    Tools.callApi({
      url: '/api/ec/dev/share/getGroupMembers',
      method: 'GET',
      params: { group_ids: id, get_type: 2 },
    }).then(action(result => result))
  )

  // 打开回话列表
  @action sendMsg = (shareParams, params, successCallback) => {
    Tools.callApi({
      url: shareParams.url ? shareParams.url : '/api/common/chatResource/addshare',
      method: 'POST',
      params: shareParams,
    }).then((addShareRes) => {
      if (addShareRes.success) {
        if (this.isInEM) { // em7
          window.em.sendMsg({
            idType: 1, // 人员ID类型，0表示EM系统ID，1表示集成系统ID
            sysId: window.localStorage.emobile_ec_id, // EM中添加的集成系统的ID
            msgType: 10, // 消息类型：1-文本 2-链接 10-EC分享消息
            ...params,
            success: () => {
              if (successCallback && typeof successCallback === 'function') {
                successCallback();
              }
              this.throwSuccess();
            },
            fail: (sendRes) => {
              this.throwError(JSON.stringify(sendRes));
              // this.throwError(sendRes.errMsg)
            },
          });
        } else { // 企业微信 钉钉
          const sendMsgParams = {
            sysid: window.localStorage.emobile_ec_id,
            ...params,
          };
          Tools.callApi({
            url: '/api/ec/dev/share/sendwx',
            method: 'POST',
            params: { data: JSON.stringify(sendMsgParams) },
          }).then((res) => {
            if (res.status && res.data.errcode === 0) {
              if (successCallback && typeof successCallback === 'function') {
                successCallback();
              }
              this.throwSuccess();
            } else {
              // this.throwError(res.data && res.data.errmsg);
              this.throwError(JSON.stringify(res.data));
            }
          });
        }
      } else {
        // this.throwError(addShareRes.errorMsg);
        // 流程分享报错提示信息统一
        this.throwError(`${getLabel('509932', '暂无分享权限')}!`);
      }
    });
  }

  @action throwSuccess = () => Toast.success(getLabel(391211, '分享成功！'), 1);

  @action throwError = msg => Toast.offline(msg || getLabel(391212, '分享失败！'), 1);

  @action setStoreState = params => Object.keys(params).forEach(key => this[key] = params[key])

  // 搜索数据过滤
  @action doChatFilter = (name) => {
    const filterName = name.toUpperCase();
    const resultData = this.sourceChatList.filter(v => v.target_name.toUpperCase().indexOf(filterName) > -1 || (v.py_all && v.py_all.toUpperCase().indexOf(filterName) > -1) || (v.py && v.py.toUpperCase().indexOf(filterName) > -1));
    this.chatList = resultData;
  }

  @action doGroupFilter = (name) => {
    const filterName = name.toUpperCase();
    const resultData = this.sourceGroupList.filter(v => v.group_name.toUpperCase().indexOf(filterName) > -1 || (v.py_all && v.py_all.toUpperCase().indexOf(filterName) > -1) || (v.py && v.py.toUpperCase().indexOf(filterName) > -1));
    this.groupList = resultData;
  }
}
